package com.authsphere.common.result;

import com.authsphere.common.utils.ObjectTypeUtils;
import com.google.common.net.MediaType;
import jakarta.servlet.http.HttpServletResponse;

import java.util.Objects;

/**
 * @program: AuthSphere
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/13 21:28
 **/
public class ResponseResultUtils {


    public static void result(final HttpServletResponse response, final Object result) {
        result(response, result, HttpServletResponse.SC_OK);
    }

    public static void result(final HttpServletResponse response, final Object result, final int status) {
        if (Objects.isNull(result)) {
            return;
        }
        Object resultData = ResponseResult.format(response, result);
        MediaType mediaType = MediaType.PLAIN_TEXT_UTF_8;
        if (!ObjectTypeUtils.isBasicType(result)) {
            mediaType = ResponseResult.contentType(response, result);
        }
        response.setContentType(mediaType.toString());
        final Object responseData = ResponseResult.result(response, resultData);
        assert responseData != null;
        try {
            response.setStatus(status);
            response.getWriter().write(responseData.toString());
            response.flushBuffer();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
